from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

db = SQLAlchemy()
login_manager = LoginManager()


# # Define the Article model
# class Article(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     title = db.Column(db.String(100), nullable=False)
#     content = db.Column(db.Text, nullable=False)
#     updated_at = db.Column(db.DateTime, nullable=False)

#     def __repr__(self):
#         return f"Article('{self.title}', '{self.updated_at}')"


from sqlalchemy import Column, Integer, String, Text, DateTime, func
from sqlalchemy.sql.expression import text
from sqlalchemy.orm import relationship


class Article(db.Model):
    __tablename__ = 'articles'
    
    id = Column(Integer, primary_key=True)
    title = Column(String(255), nullable=False)
    created_at = Column(DateTime, server_default=func.current_timestamp())
    updated_at = Column(DateTime, server_default=func.current_timestamp(), onupdate=func.current_timestamp())
    category = Column(String(255), nullable=False)
    tags = Column(Text)
    content = Column(Text, nullable=False)
    view_count = Column(Integer, default=0)
    author_id = Column(Integer, db.ForeignKey('user.id'))
    author = relationship('User', backref=db.backref('posts', lazy=True))

    def __repr__(self):
        return f"Article('{self.title}', '{self.updated_at}')"

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))



from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True)
    password_hash = db.Column(db.String(128))

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

